<?php
/**
 * 全局自定义辅助函数
 * Created by PhpStorm.
 * User: jinqiang
 * Date: 2018/12/7
 * Time: 20:53
 */

use Illuminate\Support\Facades\Redis;

/**
 * 获取指定长度的随机码
 */
if (!function_exists('randCode')) {
    function randCode($long = 4, $code = '0123456789abcdefghijkmnpqrstuvwxyz')
    {
        $res = '';
        $size = strlen($code);
        for ($i = 0; $i < $long; $i++) {
            $res .= $code[rand(0, $size - 1)];
        }
        return $res;
    }
}

/**
 * 返回数据
 */
if (!function_exists('result')) {
    function result($data = [], $msg = '获取数据')
    {
        $response = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data
        ];
        return response()->json($response);
    }
}

/**
 * 返回成功
 */
if (!function_exists('success')) {
    function success($msg = '操作成功', $data = [])
    {
        $response = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data
        ];
        return response()->json($response);
    }
}

/**
 * 返回失败
 */
if (!function_exists('error')) {
    function error($msg = '操作失败', $data = [], $code = -1)
    {
        $response = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return response()->json($response);
    }
}

/**
 * 生成唯一字符串
 */
if (!function_exists('getID')) {
    function getID($str)
    {
        $m = md5($str);
        $res = "";
        for ($i = 0; $i < 24; $i++) {
            $res .= dechx(hexdec($m[$i]) ^ hexdec($m[$i + 8]));
        }
        return $res;
    }
}

/* http 接口请求 */
if(!function_exists('httpCurl')){
    /**
     * @param $param
     * [
     *     "timeout" => 30 默认
     *     "json" => []
     *     "headers" => []
     * ]
     */
    function httpCurl($url, $param = [], $type = "post")
    {
        $json = $param['json'] ?? [];
        $headers = $param['headers'] ?? [];
        $timeout = $param['timeout'] ?? 30;
        $curl = curl_init();
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_HEADER, false); //显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_USERAGENT ,  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36') ;
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);//设置超时
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        if (strtoupper($type) == "POST") {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        }
        if(strtoupper($type) == "FILE"){//图片、文件上传类型
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        }
        if(strtoupper($type) == "PUT"){
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}

/**
 *请求接口curl
 */
if (!function_exists('httpClient')) {
    function httpClient($url, $form = [], $type = 'get')
    {
        try {
            $client = new \GuzzleHttp\Client();
            $res = $client->request($type, $url, $form);
            if ($res->getStatusCode() != 200) {
                return ['code' => -1, 'msg' => $res];
            }
            if (isset($form['form_params'])) {
                return $res->getBody()->getContents();
            }
            $body = json_decode($res->getBody(), true);
            return $body;
        } catch (Exception $e) {
            $code = 500;
            $msg = "500 Error: 接口请求错误";
            if (preg_match('/timed out/is', $e->getMessage())) {
                $code = 504;
                $msg = "504 Error: 接口请求超时";
            }
            return ['code' => $code, 'msg' => $msg, 'data' => $e->getMessage()];
        }
    }
}

/**
 * 管道模式，执行linux命令
 */
if (!function_exists('ppopen')) {
    function ppopen($cmd)
    {
        $res = '';
        $ft = popen($cmd, 'r');
        while (!feof($ft)) {
            $res .= fgets($ft, 2048);
        }
        pclose($ft);
        return $res;
    }
}

/**
 * 合成图片的标题处理
 */
if (!function_exists('splitContent')) {
    function splitContent($string)
    {
        $string = preg_replace('/[\n\r]/is', '', $string);
        $p = 78;
        $zhLen = mb_strlen($string);
        $str = "";
        $len = 0;
        for ($i = 0; $i < $zhLen; $i++) {
            $s = mb_substr($string, $i, 1);
            $len += strlen($s) < 3 ? 2 : 3;
            if ($len > $p) {
                $len = 0;
                $str .= "\n" . $s;
            } else {
                $str .= $s;
            }
        }
        return $str;
    }
}

/**
 * 去除 空行内容
 */
if (!function_exists('removeEmptyLine')) {
    function removeEmptyLine($string, $split = "\r")
    {
        $arr = explode($split, $string);
        $content = "";
        foreach ($arr as $value) {
            $value = trim($value);
            !empty($value) && $content .= (empty($content) ? "" : $split) . $value;
        }
        return $content;
    }
}

/**
 * 获取服务器host地址
 */
if (!function_exists('getServerHost')) {
    function getServerHost($serverKey, $id)
    {
        return Redis::hget($serverKey, $id);
    }
}

/**
 * 关键词替换
 */
if (!function_exists('replaceWord')) {
    function replaceWord($replaceWord, $str)
    {
        try {
            if (is_array($replaceWord) && isset($replaceWord[0]) && isset($replaceWord[1])
                && !empty($replaceWord[0]) && !empty($replaceWord[1])) {
                return str_replace($replaceWord[0], $replaceWord[1], $str);
            }
            return $str;
        } catch (Exception $e) {
            return $str;
        }
    }
}

/**
 * 是否匹配到关键词
 */
if (!function_exists('matchWord')) {
    function matchWord($filterWord, $str)
    {
        try {
            if (empty($filterWord)) {
                return false;
            }
            if (is_array($filterWord)) {
                foreach ($filterWord as $val) {
                    if (strstr($str, $val)) {
                        return true;
                    }
                }
            } else {
                return strstr($str, $filterWord);
            }
        } catch (Exception $e) {
            return false;
        }
        return false;
    }
}

/**
 * 判断是否json字符串
 */
if(!function_exists('isJson')){
    function isJson($string) {
        if (!is_string($string)) {
            return false;
        }
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }
}

/**
 * 数字转大写  $amount 金额  $type 0带小数点 1不带小数点
 */
if(!function_exists('amountNumToZn')){
    function amountNumToZn($amount, $type = 0) {
        // 判断输出的金额是否为数字或数字字符串
        if(!is_numeric($amount)){
            return ['code' => -1, 'msg' => "要转换的金额只能为数字!"];
        }
        // 金额为0,则直接输出"零元整"
        if($amount == 0) {
            return ['code' => -1, 'msg' => "人民币零元整"];
        }
        // 金额不能为负数
        if($amount < 0) {
            return ['code' => -1, 'msg' => "要转换的金额不能为负数!"];
        }
        // 金额不能超过万亿,即12位
        if(strlen($amount) > 12) {
            return ['code' => -1, 'msg' => "要转换的金额不能为万亿及更高金额!"];
        }
        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);
        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);
        // 将整数部分替换成大写汉字
        $result = '';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if($integerArr[$i] != 0){
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            }else{
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }
        // 如果小数位也要转换
        if($type == 0 && ($amountArr[1] ?? "")){
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if(isset($decimalArr[0]) && $decimalArr[0] != 0){
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if(isset($decimalArr[1]) && $decimalArr[1] != 0){
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        }else{
            $result = $result . '整';
        }
        return $result;
    }
}

